import base64
import os

from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from users.models import User


class OauthQQUserViewSerializer(serializers.ModelSerializer):  # 当时继承错了Serializer，导致没有password这个字段
    # 增加字段
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    access_token = serializers.CharField(label='加密的openid', write_only=True)
    token = serializers.CharField(label='jwt token', read_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = User
        fields = ('mobile', 'password', 'sms_code', 'access_token', 'id', 'username', 'token')
        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 检测数据  校验参数完整性 手机号的格式 短信验证码 access_token是否有效
    # def validate(self, attrs):  # access_token 为加密后的openid
    #
    #     # 1、检测access_token 是否存在
    #     access_token = attrs['access_token']
    #     openid = OAuthQQ.check_save_user_token(access_token)
    #     if openid is None:
    #         raise serializers.ValidationError('无效的access_token')
    #
    #     attrs['openid'] = openid
    #
    #     # 2、检测短信验证码
    #     mobile = attrs['mobile']
    #
    #     # 获取redis链接
    #     redis_conn = get_redis_connection('verify_codes')
    #     real_sms_code = redis_conn.get('sms_%s' % mobile)  # 这里得到是bytes类型
    #     if real_sms_code is None:
    #         raise serializers.ValidationError('验证码已过期')
    #     sms_code = attrs['sms_code']  # 字符串类型
    #     if real_sms_code.decode() != sms_code:
    #         raise serializers.ValidationError('短信验证码错误')
    #
    #     # 3、检测用户名是否存在  如果存在就检验密码
    #     try:
    #         user = User.objects.get(mobile=mobile)
    #     except User.DoesNotExist:
    #         user = None
    #     else:
    #         # 说明mobile已经注册
    #         password = attrs['password']
    #         if not user.check_password(password):
    #             raise serializers.ValidationError('密码错误')
    #
    #     attrs['user'] = user
    #
    #     return attrs
    #
    # # 4、创建新用户
    # def create(self, validated_data):
    #     """
    #     validated_data 校验后的数据 字典类型
    #
    #     """
    #     user = validated_data['user']
    #     print(validated_data['password'])
    #     if user is None:
    #         # 1、说明用户未注册，先创建一个用户 在进行绑定
    #         mobile = validated_data['mobile']
    #         password = validated_data['password']
    #         # 2、随机生成一个用户名
    #         username = base64.b64encode(os.urandom(9)).decode()
    #         User.objects.create_user(mobile=mobile, password=password, username=username)
    #
    #     # 3、保存登录绑定的qq用户数据
    #     OAuthQQUser.objects.create(user=user, openid=validated_data['openid'])
    #
    #     # 4、服务器生成一个jwt token字符串，保留用户信息
    #     from rest_framework_jwt.settings import api_settings
    #
    #     # 生成payload 的方法
    #     jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    #     # 生成jwt token方法
    #     jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    #
    #     # 生成payload
    #     payload = jwt_payload_handler(user)
    #     token = jwt_encode_handler(payload)
    #
    #     # 给user对象添加token属性
    #     user.token = token
    #
    #     return user

    def validate(self, attrs):
        """
        attrs: 数据校验时传入字典数据
        """
        # access_token是否有效
        access_token = attrs['access_token']

        openid = OAuthQQ.check_save_user_token(access_token)

        if openid is None:
            # access_token解密实现
            raise serializers.ValidationError('无效的access_token')

        attrs['openid'] = openid

        # 短信验证码是否正确
        mobile = attrs['mobile']

        # 获取redis链接
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get('sms_%s' % mobile)  # None bytes

        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')

        # 对比短信验证码
        sms_code = attrs['sms_code']  # str

        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        # 如果mobile已注册，校验对应的密码是否正确
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # `mobile`未注册
            user = None
        else:
            # `mobile`已注册
            password = attrs['password']

            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')

        attrs['user'] = user

        return attrs

    def create(self, validated_data):
        """
        validated_data: 字典，校验之后的数据
        """
        user = validated_data['user']  # None

        if user is None:
            # 如果`mobile`未注册，先创建一个新用户，然后再进行绑定
            mobile = validated_data['mobile']
            password = validated_data['password']
            # 随机生成一个用户名
            username = base64.b64encode(os.urandom(9)).decode()
            user = User.objects.create_user(username=username, mobile=mobile, password=password)

        # 保存绑定QQ登录数据
        OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )

        # 服务器生成一个jwt token字符串：保存用户的身份信息
        from rest_framework_jwt.settings import api_settings

        # 生成payload方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 生成payload
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)

        # 给user对象增加token属性：保存jwt token数据
        user.token = token

        return user
